package com.sgcc.pda.mdrh.task.safe.jsbridge;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;

import com.google.gson.Gson;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.hzaidl.IHZAidlCallback;
import com.sgcc.pda.hzaidl.api.InterfaceFactory;
import com.sgcc.pda.hzaidl.entity.CommonErrorBean;
import com.sgcc.pda.hzaidl.entity.RequestBean;
import com.sgcc.pda.hzaidl.entity.ResponseBean;
import com.sgcc.pda.hzaidl.error.HZErrorCode;
import com.sgcc.pda.mdrh.h5.library.BridgeWebView;
import com.sgcc.pda.mdrh.h5.library.CallBackFunction;
import com.sgcc.pda.mdrh.h5.router.H5BridgeHandler;
import com.sgcc.pda.mdrh.task.safe.R;
import com.sgcc.pda.mdrh.task.safe.router.SafeRouter;
import com.sgcc.pda.mdrh.task.safelibrary.BuildConfig;
import com.sgcc.pda.mdrh.widget.HzBaseWidget;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;
import com.sgcc.pda.mdrh.zoom.router.BasicRouter;
import com.sgcc.pda.mdrh.zoom.router.BusinessRouter;
import com.sgcc.pda.mdrh.zoom.router.GisRouter;
import com.sgcc.pda.mdrh.zoom.router.SsalRouter;
import com.sgcc.pda.mdrh.zoom.router.WebRouter;
import com.sgcc.pda.zoom.HardwareBinderUtil;

/**
 * Created by cj on 2020/4/24.
 */
public class MdrhH5Widget extends HzBaseWidget {

    private static final String TAG = "h5";

    BridgeWebView webView;


    @Override
    public void onCreate(Context context) {
        super.onCreate(context);

        webView = findViewById(R.id.webView);
        if (webView != null) {
            webView.registerHandler("post", new H5BridgeHandler() {
                @Override
                public void mixHandler(String data, final RequestBean requestBean, final CallBackFunction function) {

                    try {

                        String mainCode = requestBean.getMainCode();
                        //hardware请求透明转发即可
                        if (mainCode.equals("hardware")) {
                            String post = HardwareBinderUtil.getInstance().post(data, new IHZAidlCallback.Stub() {
                                @Override
                                public void callback(String s) throws RemoteException {
                                    function.onCallBack(s);
                                }
                            });
                            InterfaceFactory.InterfaceBean anInterface = InterfaceFactory.getInterface(requestBean.getMethodName());
                            if (anInterface != null && !anInterface.isAsync()) {
                                function.onCallBack(post);
                            }
                        }
                        String methodName = requestBean.getMethodName();
                        //方法名校验
                        InterfaceFactory.InterfaceBean interfaceBean = InterfaceFactory.getInterface(methodName);
                        if (interfaceBean == null) {
                            callbackFail(function, HZErrorCode.ERROR_1005, methodName);
                            return;
                        }
                        //获取router并校验
                        BaseOperateRouter router = getRouter(mainCode);
                        if (router == null) {
                            callbackFail(function, HZErrorCode.ERROR_1002, requestBean.getTag());
                            return;
                        }

                        if (interfaceBean.isAsync()) {
                            //异步返回
                            router.handleResult(getContext(), requestBean, new BaseOperateRouter.CompleteListener() {
                                @Override
                                public void complete(int retCode, String result) {
                                    if (retCode == 1) {
                                        //成功回调
                                        callbackSuccess(result, function, requestBean.getTag());
                                    } else if (retCode == 2) {
                                        //进度回调
                                        callbackProgress(result, function, requestBean.getTag(), requestBean.getMethodName());
                                    } else if (retCode == 0) {
                                        //失败回调
                                        callbackFail(function, result, requestBean.getTag());
                                    }
                                }
                            });
                        } else {
                            //需要同步结果
                            String s = router.handleResult(getContext(), requestBean, null);
                            String result = s == null ? fail(HZErrorCode.ERROR_1000, requestBean.getTag()) : success(s, requestBean.getTag());
                            function.onCallBack(result);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                        callbackFail(function, HZErrorCode.ERROR_1000, e.getMessage(), requestBean.getTag());
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {

    }

    @Override
    public void onPause() {

    }

    @Override
    public void onDestroy(Context context) {

    }


    /**
     * 根据mainCode获取对应的router。
     */
    private BaseOperateRouter getRouter(String mainCode) {
        BaseOperateRouter router = null;
        switch (mainCode) {
            case "web":
                if (BuildConfig.ISSSAL) {
                    router = new SsalRouter();
                } else {
                    router = new WebRouter();
                }
                break;
            case "basic":
                router = new BasicRouter();
                break;
            case "gis":
                router = new GisRouter();
                break;
            case "business":
                router = new BusinessRouter();
                break;
            case "safe"://安全服务
                router = new SafeRouter();
                break;
        }
        return router;
    }


    /**
     * 生成返回数据ResponseBean
     *
     * @param retCode 返回码
     * @param msgJson 返回数据json格式
     * @param tag     请求标识
     */
    private ResponseBean createResponseBean(int retCode, String msgJson, String tag) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.setRetCode(retCode);
        responseBean.setMsgJson(msgJson);
        responseBean.setTag(tag);
        return responseBean;
    }

    /**
     * 错误返回
     *
     * @param errorCode 错误码
     * @param detailMsg 追加信息
     * @param tag       请求标识
     */
    private String fail(HZErrorCode errorCode, String detailMsg, String tag) {
        CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode.getCode(), errorCode.getErrMessage() + "，" + detailMsg);
        ResponseBean responseBean = createResponseBean(0, new Gson().toJson(commonErrorBean), tag);
        return new Gson().toJson(responseBean);
    }

    private String fail(HZErrorCode errorCode, String tag) {
        CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode);
        ResponseBean responseBean = createResponseBean(0, new Gson().toJson(commonErrorBean), tag);
        return new Gson().toJson(responseBean);
    }

    private String fail(String msgJson, String tag) {
        ResponseBean responseBean = createResponseBean(0, msgJson, tag);
        return new Gson().toJson(responseBean);
    }

    private String success(String msgJson, String tag) {
        ResponseBean responseBean = createResponseBean(1, msgJson, tag);
        return new Gson().toJson(responseBean);
    }

    /**
     * 回调返回错误结果
     *
     * @param errorCode 错误码
     * @param callback  回调方法
     * @param detailMsg 追加信息
     */
    private void callbackFail(final CallBackFunction callback, final HZErrorCode errorCode, final String detailMsg, final String tag) {
        if (callback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    callback.onCallBack(fail(errorCode, detailMsg, tag));
                }
            });
        }
    }

    /**
     * 回调返回错误结果
     *
     * @param errorCode 错误码
     * @param callback  回调方法
     */
    private void callbackFail(final CallBackFunction callback, final HZErrorCode errorCode, final String tag) {
        if (callback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    callback.onCallBack(fail(errorCode, tag));
                }
            });
        }
    }

    /**
     * 回调返回错误结果
     *
     * @param msgJson  返回的json
     * @param callback 回调方法
     */
    private void callbackFail(final CallBackFunction callback, final String msgJson, final String tag) {
        if (callback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("返回H5请求失败：" + fail(msgJson, tag));
                    callback.onCallBack(fail(msgJson, tag));
                }
            });
        }
    }

    /**
     * 回调返回正确结果
     */
    public void callbackSuccess(final String msgJson, final CallBackFunction callback, final String tag) {
        if (callback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("返回H5请求成功：" + success(msgJson, tag));
                    callback.onCallBack(success(msgJson, tag));
                }
            });
        }
    }

    /**
     * 回调返回过程信息
     */
    public void callbackProgress(String msgJson, CallBackFunction callback, String tag, final String methodName) {
        if (callback != null) {
            ResponseBean responseBean = createResponseBean(2, msgJson, tag);
            final String s = new Gson().toJson(responseBean);
            if (webView != null) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        webView.callHandler("postCallback_" + methodName, s, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                LogUtil.d(TAG, "java调用js的返回数据: " + data);
                            }
                        });
                    }
                });
            } else {
                LogUtil.e("bridgeWebVeiw == null");
            }
        }
    }
}
